package com.qfedu.knowledge.filter;

import com.github.pagehelper.util.StringUtil;
import com.qfedu.knowledge.entity.enums.ResultEnum;
import com.qfedu.knowledge.exception.CaptchaException;
import com.qfedu.knowledge.handle.MyAuthenticationFailureHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName CaptchaFilter
 * @Author ykx
 * @Date 2024/5/21 15:04
 * @Version 1.0
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    private MyAuthenticationFailureHandle myAuthenticationFailureHandle;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = request.getRequestURI();
        try {
            if ("/knowledge/login".equals(url) && request.getMethod().equals("POST")) {
                validate(request);
            }
        } catch (AuthenticationException e) {
            myAuthenticationFailureHandle.onAuthenticationFailure(request, response, e);
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 校验验证码逻辑
     *
     * @param request 本次请求
     */
    private void validate(HttpServletRequest request) {
        // 用户输入的验证码
        String code = request.getParameter("code");
        // kaptcha:正确的验证码
        String kaptcha = (String) request.getSession().getAttribute("kaptcha");
        if (StringUtil.isEmpty(kaptcha)) {
            throw new CaptchaException(ResultEnum.KAPTCHA_EXPIRE);
        }
        if (!kaptcha.equalsIgnoreCase(code)) {
            throw new CaptchaException(ResultEnum.KAPTCHA_ERROR);
        }
    }

}
